package com.shj.service.impl;

import com.shj.dao.SysFamilyMapper;
import com.shj.entity.SysFamily;
import com.shj.entity.SysPerson;
import com.shj.service.SysFamilyService;
import com.shj.service.SysPersonService;
import com.shj.util.MyTimeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class SysFamilyServiceImpl implements SysFamilyService {
    @Autowired
    private SysFamilyMapper sysFamilyMapper;
    @Autowired
    private SysPersonService sysPersonService;

    @Override
    public List<SysFamily> findAll() {
        return sysFamilyMapper.findAll();
    }

    @Override
    public SysFamily findByFamilyCode(String code) {
        return sysFamilyMapper.selectByPrimaryKey(code);
    }

    /**
     * 新增家庭信息和户主信息
     * @param sysFamily
     * @param sysPerson
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(SysFamily sysFamily, SysPerson sysPerson) {
        // 生成家庭编号
        String familyCode = creatFCode(sysFamily.getGroupno());
        // 生成户主编号
        String perNo = sysPersonService.creatPerNo(familyCode);
        // 添加家庭档案信息
        sysFamily.setFamicode(familyCode);
        sysFamily.setPerscode(perNo);
        sysFamily.setPopunum(1);
        sysFamily.setAgrinum(1);
        sysFamily.setCreattime(MyTimeUtil.getNowTime());
        sysFamilyMapper.insert(sysFamily);
        // 添加户主信息
        sysPerson.setPersCode(perNo);
        sysPersonService.add(familyCode, sysPerson);
    }

    @Override
    public void edit(SysFamily sysFamily) {
        sysFamilyMapper.updateByPrimaryKey(sysFamily);
    }

    @Override
    public void delete(String code) {
        sysFamilyMapper.deleteByPrimaryKey(code);
    }

    /**
     * 自动生成家庭编号
     * @param groupNo
     * @return
     */
    @Override
    public String creatFCode(String groupNo) {
        String maxCode = sysFamilyMapper.getMaxFCode(groupNo);
        int number=1;
        if(maxCode!=null){
            int beginIndex=maxCode.length()-4;
            String no=maxCode.substring(beginIndex);
            number=Integer.parseInt(no);
            ++number;
            //使用0补足位数
            no=String.format("%04d", number);
            maxCode=groupNo+no;
        }else{
            String no=String.format("%04d", number);
            maxCode=groupNo+no;
        }
        return maxCode;
    }

    /**
     * 家庭人口数自增
     * @param familyNo
     * @param agriNum
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void countNum(String familyNo, int agriNum) {
        sysFamilyMapper.countNum(familyNo, agriNum);
    }
}
